package SingleThread;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

import javax.swing.text.html.HTMLEditorKit;

public class Majneh {

	public static void main(String[] args) {
		Queue<URL> queue = new LinkedList<URL>();
		URLList list = new URLList(queue);
		long start, stop;
		int counter = 0;
		ParserGetter kit = new ParserGetter();
		HTMLEditorKit.Parser parser = kit.getParser();
		HTMLEditorKit.ParserCallback callback = new LinkGetter(list);
		URL url = null;
		start = System.currentTimeMillis();
		try {
			url = new URL("http://cs.lth.se/eda095/");
		} catch (IOException ex) {
			ex.printStackTrace();
			System.err.println(ex);
		}
		while (list.getTotalSize() < 2000) {
			try {
				InputStream in;
				in = new BufferedInputStream(url.openStream());
				InputStreamReader r = new InputStreamReader(in);
				parser.parse(r, callback, true);
			} catch (IOException e) {
				url = queue.poll();
				continue;
				
			}
				url = queue.poll();
				if (url == null) {
					System.out.println("Links found = " + counter
							+ " < 2000. Exiting...");
					System.exit(0);
				}
			counter++;
		}
		stop = System.currentTimeMillis();
		Iterator<URL> itr = list.getLinks().iterator();
		System.out.println("List of URLs:");
		while (itr.hasNext()) {
			System.out.println(itr.next());
		}
		Iterator<URL> itr2 = list.getMails().iterator();
		System.out.println("----------------------------");
		System.out.println("List of addresses:");
		while (itr2.hasNext()) {
			System.out.println(itr2.next());
		}

		System.out.println("Found 2000 links in " + (stop - start) / 1000
				+ " seconds.");
		System.out.println("Searched " + counter + " URLs");
		System.exit(0);
	}
}
